import React, { useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  Button,
  CircularProgress,
  Alert,
  Box,
  Typography,
} from '@mui/material';
import { usePost } from '../contexts/PostContext';

interface CreatePostDialogProps {
  open: boolean;
  onClose: (created?: boolean) => void;
}

export const CreatePostDialog: React.FC<CreatePostDialogProps> = ({ open, onClose }) => {
  const { createPost, user } = usePost();
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async () => {
    if (!user) {
      setError('用户未登录');
      return;
    }

    if (!title.trim()) {
      setError('标题不能为空');
      return;
    }

    if (!content.trim()) {
      setError('内容不能为空');
      return;
    }

    try {
      setLoading(true);
      setError(null);
      await createPost(content, title);
      setTitle('');
      setContent('');
      // 传递创建成功的标志
      onClose(true);
    } catch (err) {
      setError('发布帖子失败');
      console.error('发布帖子错误:', err);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
      <DialogTitle>发布新帖</DialogTitle>
      <DialogContent>
        {error && (
          <Alert severity="error" sx={{ mb: 2 }}>
            {error}
          </Alert>
        )}
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          <TextField
            margin="dense"
            label="标题"
            fullWidth
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            disabled={loading}
            placeholder="请输入帖子标题"
            required
          />
          <TextField
            margin="dense"
            label="内容"
            multiline
            rows={4}
            fullWidth
            value={content}
            onChange={(e) => setContent(e.target.value)}
            disabled={loading}
            placeholder="请输入帖子内容"
            required
          />
        </Box>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose} disabled={loading}>
          取消
        </Button>
        <Button
          onClick={handleSubmit}
          variant="contained"
          color="primary"
          disabled={loading}
          startIcon={loading ? <CircularProgress size={20} /> : null}
        >
          发布
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default CreatePostDialog;